<?php

/**
 *
 * @filename 企业端管理
 */

namespace app\admin\controller;

use app\index\model\Putlog;
use think\Controller;
use think\Db;
use expand\Yunst;
use app\admin\model\ProjectUser;
use app\admin\model\NewProject;
use app\admin\model\ApplicationForMoney;
use app\admin\model\Order;
use app\admin\model\Project;
use app\admin\model\Member as Members;
use app\admin\model\OrderPayment;
use app\admin\model\Batchpay;
use app\admin\model\MoneyReturn;
use app\admin\model\MoneyCom;
use app\admin\model\MoneyReturns;
use redis\Redis;

class ProjectSide extends Common {
    private $puModel;
    private $npModel;
    private $afmModel;
    private $orModel;
    private $pModel;
    private $mrModel;
    private $mcModel;
    private $mrsModel;
    const  UPLOAD_SRC = '/uploads/projectuser/';

    public function _initialize() {
        parent::_initialize();
        $this->puModel = new ProjectUser();
        $this->npModel = new NewProject();
        $this->afmModel =new ApplicationForMoney();
        $this->orModel = new Order();
        $this->pModel = new Project();
        $this->mrModel = new MoneyReturn();
        $this->mcModel = new MoneyCom();
        $this->mrsModel= new MoneyReturns();
    }


    /**
     *项目方管理列表
     * @author hey_heyang(635870453@qq.com)
     */

    public function ProjectManage()
    {
        $puModel = new ProjectUser();
        $where = [];
        if(input('get.project_id')){
            $where['id'] = intval(input('project_id'));
        }

        if(input('get.company_name')){
            $where['company_name'] = ['LIKE','%'.input('get.company_name').'%'];
        }
        if(isset($_GET['status']) && $_GET['status']!='' && intval($_GET['status']!=-1)){
            $where['status'] = ['eq',intval(input('get.status'))];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = $order[0] . ' ' . $order[1];
        } else {
            $order = 'id desc';
        }
        $where['id'] = ['not in',[1,9]]; //屏蔽阿拉巴里与华音律风文化
        $dataList = $puModel->where($where)->order($order)->paginate(10, false, page_param());
        if(input('down')){
            $tableHeader = ['项目方ID','项目方名称','法人姓名','法人手机号','审核状态','备注信息'];
            $excel_data = $puModel->where($where)->order($order)->select()->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['company_name'] = $v['company_name'];
                $data[$k]['legal_person'] = $v['legal_person'];
                $data[$k]['mobile'] = $v['mobile'];
                if ($v['status'] == 0) {
                    $data[$k]['status'] = '待提交';
                    $data[$k]['msg'] = '';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '已提交';
                    $data[$k]['msg'] = '';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '等待通联审核';
                    $data[$k]['msg'] = '';
                } elseif ($v['status'] == 3) {
                    $data[$k]['status'] = '已拒绝';
                    $data[$k]['msg'] = $v['systerm_msg'];
                }elseif ($v['status'] == 4) {
                    $data[$k]['status'] = '通联已拒绝';
                    $data[$k]['msg'] =$v['tonglian_msg'];
                }elseif ($v['status'] == 5) {
                    $data[$k]['status'] ='已通过';
                    $data[$k]['msg'] ='';
                }
            }
            ToPHPEXECL($tableHeader,$data,'项目方列表');   //下载数据列表
        }
        $this->assign('dataList', $dataList);
        $this->assign('status', $_GET['status']);
        return $this->fetch();
    }


    /**
     *项目列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function ProjectList()
    {
        $npModel = new NewProject();
        $where = [];
        if(input('get.project_name')){
            $where['np.project_name'] = ['LIKE','%'.input('get.project_name').'%'];
        }
        if(isset($_GET['status']) && $_GET['status']>0){
            $where['np.status'] = ['eq',intval(input('get.status'))];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'np.'.$order[0] . ' ' . $order[1];
        } else {
            $order = 'np.id desc';
        }
        $filed='np.*,FROM_UNIXTIME(np.create_time) as time,pu.company_name';
        $pagesize = 10;
        $dataList=$npModel->alias('np')->join('project_user pu','np.company_id=pu.id')->where($where)->field($filed)->order($order)->paginate($pagesize,false,page_param());
        if(input('down')){
            $tableHeader = ['项目ID','项目名称','申请金额','项目方','状态','创建时间'];
            $excel_data = $npModel->alias('np')->join('project_user pu','np.company_id=pu.id')->where($where)->field($filed)->order($order)->select()->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['target_code'] = $v['target_code'];
                $data[$k]['company_name'] = $v['company_name'];
                if ($v['status'] == 1) {
                    $data[$k]['status'] = '待审核';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '已通过';
                } elseif ($v['status'] == 3) {
                    $data[$k]['status'] = '已拒绝';
                }
                $data[$k]['time'] = $v['time'];
            }

            ToPHPEXECL($tableHeader,$data,'企业端项目列表');   //下载数据列表
        }
        $this->assign('dataList', $dataList);
        $this->assign('status', $_GET['status']);
        return $this->fetch();
    }

    /**
     *项目详情
     * * @param  $id 项目id
     * @author hey_heyang(635870453@qq.com)
     */

    public function detailProject($id){
        if($id){
            $filed='np.*,pu.company_name,pu.id as company_id';
            $project_info =$this->npModel->alias('np')->join('project_user pu','np.company_id=pu.id')->where(array('np.id'=>intval($id)))->field($filed)->find();
            if(!empty($project_info)){
                $project_info['appendix_file_name'] = $project_info['appendix'];
                $appendix=self::UPLOAD_SRC.$project_info['company_id'].'/'.$project_info['appendix'];
                $project_info['appendix'] = $appendix;
                $this->assign('project_info',$project_info);
                return $this->fetch();
            }
        }else{
            $this->redirect('ProjectList');
        }
        return $this->fetch();
    }


    /**
     *项目审核页面
     * @param  $id 项目id
     * @author hey_heyang(635870453@qq.com)
     */

    public function checkProject($id){
        if($id){
            $filed='np.*,pu.company_name,pu.id as company_id';
            $project_info =$this->npModel->alias('np')->join('project_user pu','np.company_id=pu.id')->field($filed)->where(array('np.id'=>$id))->find();
            if(!empty($project_info)){
                $project_info['appendix_file_name'] = $project_info['appendix'];
                $appendix=self::UPLOAD_SRC.$project_info['company_id'].'/'.$project_info['appendix'];
                $project_info['appendix'] = $appendix;
                $this->assign('project_info',$project_info);
                return $this->fetch();
            }
        }else{
            $this->redirect('ProjectList');
        }
    }

    /**
     *项目审核提交
     * @author hey_heyang(635870453@qq.com)
     */
    public function projectInfoConfirm(){
        if(request()->isAjax() && request()->isPost()){
            $id=intval($_POST['id']);
            $systerm_check = intval($_POST['systerm_check']);
            $systerm_msg = $_POST['systerm_msg'];
            $company_id=$this->npModel->where(['id'=>$id])->value('company_id');
            if($id){
                $result = $this->npModel->confirmDetailProject($id,$systerm_check,$systerm_msg);
                $redis = Redis::instance();
                $token = $redis->get('user:' . $company_id);
                $firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
                $firm_info['modify'] = true;
                $redis->hSet('firm_info', $token, json_encode($firm_info));
                if($result['status']>0){
                     ajaxReturn('操作成功', url('ProjectList'));
                }else{
                     ajaxReturn($result['msg']);
                }
            }else{
                 ajaxReturn('参数错误');
            }
        }else{
             ajaxReturn('参数错误');
        }
    }





    /**
     * 用款申请列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function DivideMoney()
    {
        $where = [];
        if(input('get.company_name')){
            $where['pu.company_name'] = ['LIKE','%'.trim(input('get.company_name')).'%'];
        }
        if(input('get.project_name')){
            $where['np.project_name'] = ['LIKE','%'.trim(input('get.project_name')).'%'];
        }
        if(isset($_GET['status']) && $_GET['status']>0){
            $where['afm.status'] = ['eq',intval(input('get.status'))];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'afm.'.$order[0] . ' ' . $order[1];
        } else {
            $order = 'afm.id desc';
        }
        $filed='afm.*,FROM_UNIXTIME(afm.create_time) as time,pu.company_name,np.project_name';
        $pagesize = 10;
        $dataList=$this->afmModel->alias('afm')
            ->join('project_user pu','afm.company_id=pu.id')
            ->join('project np','afm.project_id=np.id')
            ->where($where)
            ->field($filed)
            ->order($order)
            ->paginate($pagesize,false,page_param());
        if(input('down')){
            $tableHeader = ['项目ID','项目名称','项目方','申请金额','状态','创建时间'];
            $excel_data = $this->afmModel->alias('afm')
                ->join('project_user pu','afm.company_id=pu.id')
                ->join('project np','afm.project_id=np.id')
                ->where($where)
                ->field($filed)
                ->order($order)
                ->select()
                ->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['target_code'] = $v['target_code'];
                $data[$k]['company_name'] = $v['company_name'];
                if ($v['status'] == 1) {
                    $data[$k]['status'] = '待审核';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '已通过';
                } elseif ($v['status'] == 3) {
                    $data[$k]['status'] = '已拒绝';
                }
                $data[$k]['time'] = $v['time'];
            }

            ToPHPEXECL($tableHeader,$data,'用款申请列表');   //下载数据列表
        }
        $this->assign('dataList', $dataList);
        $this->assign('status', $_GET['status']);
        return $this->fetch();
    }


    /**
     * 用款申请审核页面
     * @param  $id 用款申请ID
     * @author hey_heyang(635870453@qq.com)
     */
    public function detailDivideMoney($id){
        if($id){
            $filed='afm.*,FROM_UNIXTIME(afm.create_time) as time,pu.company_name,np.project_name';
            $project_info = $this->afmModel->alias('afm')
                ->join('project_user pu','afm.company_id=pu.id')
                ->join('project np','afm.project_id=np.id')
                ->where(array('afm.id'=>$id))
                ->field($filed)
                ->find();
            if(!empty($project_info)){
                $this->assign('project_info',$project_info);
                return $this->fetch();
            }
        }else{
            $this->redirect('DivideMoney');
        }
    }

    /**
     *用款审核提交
     * @author hey_heyang(635870453@qq.com)
     */
    public function detailDivideCheck(){
        if(request()->isAjax() && request()->isPost()){
            $id=intval($_POST['id']);
            $systerm_check = intval($_POST['systerm_check']);
            $systerm_msg = $_POST['systerm_msg'];
            if($id){
                $result = $this->afmModel->confirmDetailDivide($id,$systerm_check,$systerm_msg);
                if($result['status']>0){
                     ajaxReturn('操作成功', url('DivideMoney'));
                }else{
                    ajaxReturn($result['msg']);
                }
            }else{
                 ajaxReturn('参数错误');
            }
        }else{
             ajaxReturn('参数错误');
        }
    }




    /**
     * 项目代付列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function ProjectDaiFu()
    {
        $where = [];
        $where['or.status'] = ['gt',1];
        $where['or.type'] = ['eq',1];
        if(input('get.project_id')){   // 项目id
            $where['pr.id'] = intval(input('project_id'));
        }
        if(intval(input('get.series_number'))>0 && input('get.relevance_id')){    //申请期数，只有选择了项目方，并且项目方有成功申请的期数，才会有值
           $where['or.series_number'] = intval(input('get.series_number'));
            $where['or.relevance_id'] = intval(input('get.relevance_id'));
        }
        if(isset($_GET['status']) && intval(input('get.status')) != -1 ){  //代付状态
            $where['or.payment_status'] = ['eq',intval(input('get.status'))];
        }else{
            $_GET['status']=-1;
        }

        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'or.'.$order[0] . ' ' . $order[1];
        } else {
            $order = 'or.id desc';
        }

        $projectList = $this->pModel->field('id,project_name')->select();
        if(input('get.afm_id') && input('get.has_bind_list')==1){  //用款申请列表查看详情
            $bind_res=$this->getHasBindOrderList(intval(input('get.afm_id')));
            $this->assign('dataList', $bind_res['origin_data']);
            $this->assign('total_money', $bind_res['total_money']);
            $this->assign('target_money',$bind_res['money']);
            $this->assign('is_show',0);
            $this->assign('projectList', $projectList);
            $this->assign('project_id', $_GET['project_id']);
            $this->assign('money', $_GET['money']);
            $this->assign('afm_id', $_GET['afm_id']);
            $this->assign('has_bind_list', $_GET['has_bind_list']);
            $this->assign('afm_id', intval(input('get.afm_id')));
//            $this->assign('is_page_show',1);
            return $this->fetch();
        }

        if(input('get.project_id') && floatval(trim(input('get.money')))>0){  //输入代付金额，需要做订单的筛选求和处理,跳转新页面进行结果集的操作
            $target_money = floatval(trim(input('get.money')));
            $res=$this->getMostApproachOrder(input('get.project_id'),$target_money);
            $this->assign('dataList', $res['origin_list']);
            $this->assign('total_money', $res['total_money']);
            $this->assign('target_money',$target_money);
            $this->assign('is_show',1);
            $this->assign('status', $_GET['status']);
            $this->assign('projectList', $projectList);
            $this->assign('project_id', $_GET['project_id']);
            $this->assign('money', $_GET['money']);
            $this->assign('series_number', $_GET['series_number']);
//            $this->assign('is_page_show',1);
            return $this->fetch();
        }


        $field= 'or.*,pr.project_name,pu.company_name,if(series_number>0,CONCAT(\'第\',series_number,\'期\'),\'\') as series_number,m.username,m.mobile';
        $dataList = $this->orModel->alias('or')->join('project pr','or.project_id=pr.id')
            ->join('project_user pu','pr.initiator=pu.id')
            ->join('member m','or.uid=m.id')
            ->where($where)
            ->field($field)
            ->order($order)
            ->paginate('', false, page_param());
        if(input('down')){
            $tableHeader = ['订单ID','订单号','姓名','手机号','认投金额','所属项目','项目方','状态','申请期数'];
            $excel_data = $this->orModel->alias('or')->join('project pr','or.project_id=pr.id')
                ->join('project_user pu','pr.initiator=pu.id')
                ->join('member m','or.uid=m.id')
                ->where($where)
                ->field($field)
                ->order($order)
                ->select()
                ->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['money'] = $v['money'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['company_name'] = $v['company_name'];
                if ($v['payment_status'] == 0) {
                    $data[$k]['status'] = '未代付';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '已代付';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '代付失败';
                }
                $data[$k]['series_number'] = $v['series_number'];
            }
            ToPHPEXECL($tableHeader,$data,'项目代付列表');   //下载数据列表
        }
        $this->assign('dataList', $dataList);
        $this->assign('projectList', $projectList);
        $this->assign('status', $_GET['status']);
        $this->assign('project_id', $_GET['project_id']);
        $this->assign('money', $_GET['money']);
        $this->assign('series_number', $_GET['series_number']);
//        $this->assign('is_page_show',1);
        return $this->fetch();
    }

    /**
     * 用款申请查看关联订单列表
     * @param  $id 用款申请的id
     * @author hey_heyang(635870453@qq.com)
     */

    public function getHasBindOrderList($id){
        $afm_info = $this->afmModel->where(array('id'=>$id))->find()->toArray();
        $res_data = $this->orModel->getHasBindOrder($afm_info['id']);
//        array_multisort(array_column($res_data,'payment_status'),SORT_ASC,$res_data);
        $data['origin_data'] = $res_data['origin_data'];
        $data['order_list'] = $res_data['data'];
        $data['total_money'] = $afm_info['real_money'];
        $data['target_money'] = $afm_info['money'];
        $_GET['money'] = $afm_info['money'];
        $_GET['project_id'] = $res_data['data'][0]['project_id'];
        if(input('down')){
            $tableHeader = ['订单ID','订单号','姓名','手机号','认投金额','所属项目','项目方','状态','申请期数'];
            $data=array();
            foreach ($res_data['data'] as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['money'] = $v['money'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['company_name'] = $v['company_name'];
                if ($v['payment_status'] == 0) {
                    $data[$k]['status'] = '未代付';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '已代付';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '代付失败';
                }
                $data[$k]['series_number'] = $v['series_number'];
            }
            ToPHPEXECL($tableHeader,$data,'项目代付列表');   //下载数据列表
        }
        return $data;
    }




    /**
     * 获取与代付金额匹配的订单列表
     * @param  $id 认投项目id
     * @param  $money 代付金额
     * @author hey_heyang(635870453@qq.com)
     */
    public function getMostApproachOrder($id,$money){
        if($id>0 && $money>0){
           $res_data=$this->orModel->getMostOrder($id,$money);
           $order_list=$res_data['order_list'];
//           array_multisort(array_column($res_data['order_list'],'payment_status'),SORT_ASC,$res_data['order_list']);
//           $total_money = $res_data['total_money'];
        }
        if(input('down')){
            $tableHeader = ['订单ID','订单号','姓名','手机号','认投金额','所属项目','项目方','状态','申请期数'];
            $data=array();
            foreach ($order_list as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['order_sn'] = $v['order_sn'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['money'] = $v['money'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['company_name'] = $v['company_name'];
                if ($v['payment_status'] == 0) {
                    $data[$k]['status'] = '未代付';
                } elseif ($v['status'] == 1) {
                    $data[$k]['status'] = '已代付';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '代付失败';
                }
                $data[$k]['series_number'] = $v['series_number'];
            }
            ToPHPEXECL($tableHeader,$data,'项目代付列表');   //下载数据列表
        }
        return $res_data;
    }

    /**
     * 用款申请关联订单操作
     * @param  $id 认投项目id
     * @param  $money 代付金额
     * @author hey_heyang(635870453@qq.com)
     * return string
     */
    public function sureRelated(){
        if(request()->isAjax() && request()->isPost()){
            if(empty($_POST['project_id']) || empty($_POST['money'])){
                ajaxReturn('参数错误');
            }
           $id=intval($_POST['project_id']);
           $money=floatval($_POST['money']);
           $history=$this->afmModel->getAfmInfo($id,array('status'=>2));
           $series_number = empty($history)?0:count($history);  //关联用款申请的期数
           $res = $this->afmModel->getAfmInfo($id,array('status'=>2,'relevance_status'=>1));
           if(empty($res)){
               ajaxReturn('未能成功绑定用款申请');
           }
           $related = $this->afmModel->bindProjectOrder($res[0]['id'],$series_number,$_SESSION['orderids'],$money,$id);
           if($related['status']>0){
               ajaxReturn('关联成功','/hryweb.php/project_side/ProjectDaiFu');
           }else{
              ajaxReturn($related['msg']);
           }
        }else{
            ajaxReturn('无效操作');
        }
    }



    /**
     * 订单单笔代付
     * @param  $id 订单id
     * @author hey_heyang(635870453@qq.com)
     * return string
     */
    public function signalOrderPay() {
        if(request()->isAjax() && request()->isPost()){
            if(empty($_POST['order_id'])){ajaxReturn('参数错误');}
            $id = intval($_POST['order_id']);
            $orderClass = new Order();
            $YunClass = new Yunst();
            $memberClass = new Members();
            $projectClass = new Project();
            $projectUserClass = new ProjectUser();
            $orderPaymentClass = new OrderPayment();
            $orderData = $orderClass->where(['id' => $id])->find()->toArray();
            if($orderData['payment_status']==1){
                ajaxReturn('订单已代付!');
            }
            $bizUserId = $memberClass->where(['id' => $orderData['uid']])->value('bizUserId');
            $bizOrderNo = 'HryqySDaiFu' . $id .time() . str_pad($bizUserId, 7, '0', STR_PAD_LEFT);
            $project_info = $projectClass->where(array('id'=>$orderData['project_id']))->find()->toArray();
            $companyBizUserId = $projectUserClass->where(array('id'=>$project_info['initiator']))->value('bizUserId');
            $message = $YunClass->signalAgentPayForCompany($bizOrderNo, $bizUserId, $orderData['order_sn'], $orderData['money'],$companyBizUserId);
            if ($message['status'] == 'error') {
                $orderClass->where(['id' => $orderData['id']])->update(['payment_status' => 2, 'payment_remark' => $message['message']]);
                 ajaxReturn($message['message']);
            }
            if ($message['status'] == 'OK') {
                $payment_data = [];
                $member_data = $memberClass->where(['id' => $orderData['uid']])->find();
                $payment_data['project_id'] = $orderData['project_id'];
                $payment_data['order_sn'] = $orderData['order_sn'];
                $payment_data['money'] = $orderData['money'];
                $payment_data['status'] = 2;
                $payment_data['name'] = $member_data['username'];
                $payment_data['create_time'] = $orderData['create_time'];
                $payment_data['mobile'] = $member_data['mobile'];
                $payment_data['payment_time'] = time();
                $payment_data['uid'] = UID;
                $payment_data['remark'] = $message['remark'];
                $payment_data['number_id'] = $member_data['certificate'];
                $res2 = $orderPaymentClass->insert($payment_data);
                $res3 = $orderClass->where(['id' => $orderData['id']])->update(['payment_status' => 1]);
                if(!$res2 || !$res3){
                    $error['data'] = $payment_data;
                    $error['error'] ='企业端单笔代付时,插入payment表失败，或者更新payment_status失败';
                    file_put_contents(date("Y-m-d H", time()) . 'QY_single_daifu.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }

                //代付成功后，企业会员账户余额修改
                $res = $projectUserClass->where(['id'=>$project_info['initiator']])->setInc('money', $orderData['money']);
                if(!$res){
                    $error['company_id'] = $project_info['initiator'];
                    $error['error'] ='企业端单笔代付时,更新企业账户余额失败';
                    file_put_contents(date("Y-m-d H", time()) . 'QY_single_daifu.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
                $redis = Redis::instance();
                $token = $redis->get('user:' . $project_info['initiator']);
                $firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
                $firm_info['modify'] = true;
                $redis->hSet('firm_info', $token, json_encode($firm_info));

                //判断回款订单是否回款完成，完成后向企业账户发起通知
                $afm_info = $this->afmModel->where(['id'=>$orderData['relevance_id']])->find()->toArray();
                $has_daifu_money = $this->orModel->where(['relevance_id'=>$orderData['relevance_id'],'payment_status'=>1])->sum('money');
                if($has_daifu_money == $afm_info['real_money']){
                    $res1 = $this->afmModel->where(['id'=>$orderData['relevance_id']])->update(['relevance_status'=>3]);
                    if($res1){
                        companyTobeNotice($project_info['initiator'], '用款', '已入账项目投资金额' . $afm_info['real_money'] . '元。');
                    }else{
                        $error['company_id'] = $project_info['initiator'];
                        $error['huikuan_order_id'] =$orderData['relevance_id'];
                        $error['error'] ='企业端单笔代付并且回款完成时,更新回款订单状态失败';
                        file_put_contents(date("Y-m-d H", time()) . 'QY_single_daifu.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                    }

                }
                ajaxReturn('代付成功',1);
            }
        }else{
            ajaxReturn('错误操作');
        }

    }


    /**
     * 订单批量代付
     * @param  $afm_id 用款申请ID
     * @author hey_heyang(635870453@qq.com)
     */
    public function batchOrderPay(){
        if(request()->isAjax() && request()->isPost()) {
            if(empty($_POST['afm_id'])){ajaxReturn('参数错误');}
            $afm_id = intval($_POST['afm_id']);
            $orderModel = new Order();
            $signal_order_info = $orderModel->where(array('relevance_id' => $afm_id))->find()->toArray();
            $dataList = $orderModel
                ->alias('a')
                ->field('a.uid,sum(a.money) as amount,b.bizUserId')
                ->join('tf_member b', 'a.uid=b.id')
                ->where(['a.project_id' => $signal_order_info['project_id'], 'a.status' =>2, 'payment_status' => array('neq', 1),'relevance_id'=>$afm_id])
                ->group('a.uid')
                ->limit(100)
                ->select();
            $dataList = empty($dataList)?array():$dataList->toArray();
            //如果支持订单为空
            if (empty($dataList)) {
                 ajaxReturn('未找到需要代付的订单');
            }

            $companyId = $this->afmModel->where(array('id'=>$afm_id))->value('company_id');
            $companyBizUserId = $this->puModel->where(array('id'=>$companyId))->value('bizUserId');
            $YunClass = new Yunst();
            /*批次号*/
            $Olist['order'] = 'back' . str_pad($afm_id, 4, '0', STR_PAD_LEFT);
            $list = [];
            foreach ($dataList as $value) {
                $list[] = $this->getDaiList($signal_order_info['project_id'], $value['uid'], $value['amount'], $value['bizUserId'],$companyBizUserId,$afm_id);
            }
            $Olist['list'] = $list;
            $res = $YunClass->batchPay($Olist);

            if ($res['status'] == 'OK') {
                 ajaxReturn('操作成功', 1);
            } else {
                 ajaxReturn($res['message']);
            }
        }else{
            ajaxReturn('错误操作');
        }
    }

    /**
     * 订单批量代付,订单信息格式化
     * @param  $id 认投项目ID
     * @param  $uid 会员ID
     * @param  $amount 代付金额
     * @param  $bizUserId 会员通联业务账号
     * @param  $companyBizUserId 企业会员业务账号
     * @author hey_heyang(635870453@qq.com)
     */
    private function getDaiList($id,$uid,$amount,$bizUserId,$companyBizUserId,$relevance_id){
        $dataValue = [];
        $orderModel = new Order();
        $batchModel = new Batchpay();
        $dataList = $orderModel->where(['project_id'=>$id,'uid'=>$uid,'status'=>2,'payment_status'=>array('neq',1),'relevance_id'=>$relevance_id])->order('id asc')->limit(100)->select();
        if(empty($dataList)){
            $error['project_id'] =$id;
            $error['uid'] =$uid;
            $error['error'] = '批量代付操作时，未找到相关订单信息';
            file_put_contents(date("Y-m-d H", $relevance_id.time()) . 'QYPL_daifu_error.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            return;
        }
        $dataValue['bizOrderNo'] = 'HryqyBDaiFu'.time() .str_pad($bizUserId,7,'0',STR_PAD_LEFT);
        $res = $batchModel->insert(['bizOrderNo'=>$dataValue['bizOrderNo'],'uid'=>$uid,'amount'=>$amount,'project_id'=>$id]);
        if(!$res){
            $error['bizOrderNo'] =$dataValue['bizOrderNo'];
            $error['uid'] =$uid;
            $error['project_id'] =$id;
            $error['amount'] =$amount;
            $error['error'] = '批量待代付操作时，插入批量订单出错';
            file_put_contents(date("Y-m-d H", time()) . 'QYPL_daifu_error.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }
        $collectPayList = [];
        foreach($dataList as $key=>$val){
            $collectPayList[$key]['bizOrderNo'] = $val['order_sn'];
            $collectPayList[$key]['amount'] = $val['money']*100;
        }
        $dataValue['collectPayList'] = $collectPayList;
        $dataValue['bizUserId'] = $companyBizUserId;  //指定项目方为收款人
        $dataValue['accountSetNo'] = '200232';
        $dataValue['backUrl'] = input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME').'/'.'backcall/orderBatchPay.html';
        $dataValue['amount'] = $amount*100;
        $dataValue['fee'] = 0;
//        $dataValue['splitRuleList'] = [[
//            'bizUserId' => $companyBizUserId,
//            'amount' => $amount*100,
//            'fee' => 0,
//
//        ]];
        $extend_info['relevance_id'] = $relevance_id;
        $dataValue['extendInfo'] =str_replace("\\", "", json_encode($extend_info));
        return $dataValue;
    }





    /**
     * 订单批量兑付,订单信息格式化
     * @param  $id 认投项目ID
     * @param  $uid 会员ID
     * @param  $amount 代付金额
     * @param  $bizUserId 会员通联业务账号
     * @author hey_heyang(635870453@qq.com)
     */
    private function getDuiFuDaiList($id,$uid,$amount,$bizUserId,$order_id,$mr_id){
        $dataValue = [];
        $orderModel = new Order();
        $batchModel = new Batchpay();
//        $dataList = $orderModel->where(['project_id'=>$id,'uid'=>$uid,'status'=>2,'payment_status'=>array('eq',1)])->order('id asc')->limit(100)->select();
        $mrs_order = $this->mrsModel->where(['order_id'=>$order_id,'status'=>1])->find();
        $mr_order = $this->mrModel->where(['id'=>$mrs_order['return_id'],'status'=>2])->find();
        $mrs_order = empty($mrs_order)?array():$mrs_order->toArray();
        $mr_order = empty($mr_order)?array():$mr_order->toArray();
        if(empty($mrs_order) || empty($mr_order)){
            $error['project_id'] =$id;
            $error['uid'] =$uid;
            $error['error'] = '批量兑付操作时，未找到相关订单信息';
            file_put_contents(date("Y-m-d H", time()) . 'QYPL_duifu_error.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            return;
        }
        $dataValue['bizOrderNo'] = 'HryqyBDuiFu'. $mr_id .str_pad($bizUserId,7,'0',STR_PAD_LEFT);
        $res = $batchModel->insert(['bizOrderNo'=>$dataValue['bizOrderNo'],'uid'=>$uid,'amount'=>$amount,'project_id'=>$id]);
        if(!$res){
            $error['bizOrderNo'] =$dataValue['bizOrderNo'];
            $error['uid'] =$uid;
            $error['project_id'] =$id;
            $error['amount'] =$amount;
            $error['error'] = '批量兑付操作时，插入批量订单出错';
            file_put_contents(date("Y-m-d H", time()) . 'QYPL_duifu_error.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        }

//        $collectPayList = [];
//        foreach($dataList as $key=>$val){
//            $collectPayList[$key]['bizOrderNo'] = $val['order_sn'];
//            $collectPayList[$key]['amount'] = $val['money']*100;
//        }
//        $dataValue['collectPayList'] = $collectPayList;
        $dataValue['collectPayList']= [['bizOrderNo'=>$mr_order['order_no'],'amount'=>$amount*100]];
        $dataValue['bizUserId'] = $bizUserId;
        $dataValue['accountSetNo'] = '200232';
        $dataValue['backUrl'] = input('server.REQUEST_SCHEME') . '://' . input('server.SERVER_NAME').'/'.'backcall/orderDuiFuiBatchPay.html';
        $dataValue['amount'] = $amount*100;
        $dataValue['fee'] = 0;
        $extend_info['mr_id'] = $mr_id;
        $extend_info['order_id'] = $order_id;
        $dataValue['extendInfo'] =str_replace("\\", "", json_encode($extend_info));
//        $dataValue['splitRuleList'] = [[
//            'bizUserId' => 'hryqy18113112163',
//            'amount' => $amount*100,
//            'fee' => 0,
//
//        ]];

        return $dataValue;
    }




    /**
     * 项目代付选择项目后，获取项目的用款申请期数
     * @param  $id 认投项目id
     * @author hey_heyang(635870453@qq.com)
     */
    public function getSeriesNumber($id){
        if(request()->isGet() && intval($id)>0){
            $company_id = $this->pModel->where(array('id'=>$id))->value('initiator');
            $res = $this->afmModel->where(array('company_id'=>$company_id,'status'=>2))->order('id asc')->select();
            $series_list = empty($res)?array():$res->toArray();
            $res_data = array();
            if(count($series_list)){
                foreach($series_list as $key=>$value){
                    $current_key = $key+1;
                    $res_data[$key]['series_number_string']='第'.($current_key).'期('.$value['money'].')';
                    $res_data[$key]['series_number']=$current_key;
                    $res_data[$key]['relevance_id'] = $value['id'] ;
                }
                $data['status']=1;
                $data['datas'] = $res_data;
            }else{
                $data['status']=1;
                $data['datas'] = array();
            }
          echo json_encode($data);
          exit;
        }else{
             ajaxReturn('参数错误');
        }

    }





    /**
     * 项目回款列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function ProjectHuiKuan()
    {
        $where = [];
        if(input('get.company_name')){
            $where['pu.company_name'] = ['LIKE','%'.trim(input('get.company_name')).'%'];
        }
        if(input('get.project_name')){
            $where['p.project_name'] = ['LIKE','%'.trim(input('get.project_name')).'%'];
        }

        if(input('get.order_id')){
            $where['mr.id'] =intval(trim(input('get.order_id')));
        }
        if(isset($_GET['status']) && $_GET['status']>0){
            $where['mr.status'] = ['eq',intval(input('get.status'))];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'mr.'.$order[0] . ' ' . $order[1];
        } else {
            $order = 'mr.id desc';
        }
        $filed='mr.*,FROM_UNIXTIME(mr.payment_time) as time,pu.company_name,p.project_name';
        $dataList=$this->mrModel->alias('mr')
            ->join('project_user pu','pu.id=mr.company_id')
            ->join('project p','p.id=mr.project_id')
            ->where($where)
            ->field($filed)
            ->order($order)
            ->paginate('',false,page_param());
        if(input('down')){
            $tableHeader = ['订单ID','订单号','项目名称','项目方名称','回款金额','回款备注','状态','回款时间'];
            $excel_data = $this->mrModel->alias('mr')
                ->join('project_user pu','pu.id=mr.company_id')
                ->join('project p','mr.company_id=p.initiator')
                ->where($where)
                ->field($filed)
                ->order($order)
                ->select()
                ->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['id'];
                $data[$k]['order_no'] = $v['order_no'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['company_name'] = $v['company_name'];
                $data[$k]['money'] = $v['money'];
                $data[$k]['remarks'] = $v['remarks'];
                if ($v['status'] == 1) {
                    $data[$k]['status'] = '待回款';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '已回款';
                }
                $data[$k]['time'] = $v['time'];
            }

            ToPHPEXECL($tableHeader,$data,'回款订单列表');   //下载数据列表
        }
        $this->assign('dataList', $dataList);
        $this->assign('status', $_GET['status']);
        return $this->fetch();
    }


    /**
     * 会员兑付列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function MemberDuiFu()
    {
        $where = [];
        $where['mr.status'] = 2; //回款已完成
        if(input('get.order_sn')){
            $where['or.order_sn'] = ['LIKE','%'.trim(input('get.order_sn')).'%'];
        }
        if(input('get.remarks')){
            $where['mr.remarks'] = ['LIKE','%'.trim(input('get.remarks')).'%'];
        }

        if(input('get.project_id')){
            $where['or.project_id'] =intval(input('get.project_id'));
        }
        if(isset($_GET['status']) && $_GET['status']>0){
            $where['mrs.status'] = ['eq',intval(input('get.status'))];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'or.'.$order[0] . ' ' . $order[1];
        } else {
            $order = 'or.id desc';
        }
        $filed='or.id as order_id,or.order_sn,or.money as rt_money,m.username,m.mobile,
                p.project_name,pu.company_name,mrs.money_profit,mrs.money as df_money,mrs.status,mrs.id,mr.remarks';
        $dataList=$this->orModel->alias('or')
            ->join('money_returns mrs','or.id=mrs.order_id')
            ->join('money_return mr','mrs.return_id=mr.id')
            ->join('member m','m.id=or.uid')
            ->join('project p','p.id=or.project_id')
            ->join('project_user pu','pu.id=p.initiator')
            ->where($where)
            ->field($filed)
            ->order($order)
            ->paginate('',false,page_param());
        if(input('down')){
            $tableHeader = ['认投订单号','姓名','手机号码','认投金额','所属项目','项目方','收益金额','兑付金额','备注','状态'];
            $excel_data = $this->orModel->alias('or')
                ->join('money_returns mrs','or.id=mrs.order_id')
                ->join('money_return mr','mrs.return_id=mr.id')
                ->join('member m','m.id=or.uid')
                ->join('project p','p.id=or.project_id')
                ->join('project_user pu','pu.id=p.initiator')
                ->where($where)
                ->field($filed)
                ->order($order)
                ->select()
                ->toArray();
            $data=array();
            foreach ($excel_data as $k => $v) {
                $data[$k]['id'] = $v['order_sn'];
                $data[$k]['username'] = $v['username'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['money'] = $v['rt_money'];
                $data[$k]['project_name'] = $v['project_name'];
                $data[$k]['company_name'] = $v['company_name'];
                $data[$k]['money_profit'] = $v['money_profit'];
                $data[$k]['df_money'] = $v['df_money'];
                $data[$k]['remarks'] = $v['remarks'];
                if ($v['status'] == 1) {
                    $data[$k]['status'] = '未兑付';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '已兑付';
                }
            }

            ToPHPEXECL($tableHeader,$data,'兑付订单表');   //下载数据列表
        }
        $array_page = $dataList->toArray();
        if($array_page['total']>0){
        $isShow = 1;
          }else{
        $isShow =0;
        }
        $projectList = $this->pModel->field('id,project_name')->select();
        $this->assign('projectList',$projectList);
        $this->assign('projectId',input('get.project_id'));
        $this->assign('dataList', $dataList);
        $this->assign('status', $_GET['status']);
        $this->assign('isShow',$isShow);
        return $this->fetch();
    }


    /**
     * 会员单笔兑付操作
     * @author hey_heyang(635870453@qq.com)
     */

    public function confirmDuiFu(){
        if(request()->isAjax() && request()->isPost()){
            if(empty($_POST['order_id'])){ajaxReturn('参数错误');}
            $order_id = intval($_POST['order_id']);
            $id = intval($_POST['id']);
            $orderClass = new Order();
            $YunClass = new Yunst();
            $memberClass = new Members();
            $pModel =new Project();
            $orderData = $orderClass->where(['id' => $order_id,'status'=>2,'type'=>1,'payment_status'=>1])->find();
            $mrs_order = $this->mrsModel->where(['order_id'=>$order_id,'status'=>1])->find();
            $mr_order = $this->mrModel->where(['id'=>$mrs_order['return_id'],'status'=>2])->find();
            $mrs_order = empty($mrs_order)?array():$mrs_order->toArray();
            $mr_order = empty($mr_order)?array():$mr_order->toArray();
            if(empty($orderData) || empty($mrs_order) ||empty($mr_order)){
                ajaxReturn('订单信息错误,未查询到相应订单');
            }
            $bizUserId = $memberClass->where(['id' => $orderData['uid']])->value('bizUserId');
            $bizOrderNo = 'HryqySDuiFu' . $id . str_pad($bizUserId, 7, '0', STR_PAD_LEFT);
            $message = $YunClass->signalDuiFu($bizOrderNo, $bizUserId, $mr_order['order_no'], $mrs_order['money']);
            if ($message['status'] == 'error') {
                ajaxReturn($message['message']);
            }
            if ($message['status'] == 'OK') {  //由于兑付的金额和次数不定,所以每次兑付只更新兑付记录表状态,不更新order表状态
                $res1 = $this->mrsModel->where(['id' =>$id])->update(['status' => 2]);  //兑付成功
                //代付成功后，会员账户余额修改
                $res = $memberClass->where(['id' => $orderData['uid']])->setInc('money', $mrs_order['money']);
                if(!$res || !$res1){
                    $error['uid'] = $orderData['uid'];
                    $error['mrs_id'] = $mrs_order['is'];
                    $error['error'] ='企业端单笔兑付时,更新兑付状态或者更新金额失败';
                    file_put_contents(date("Y-m-d H", time()) . 'QY_single_duifu.txt', json_encode($error,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
                if ($res) {
                    $logModel = new Putlog();
                    $log = [
                        'uid' => $orderData['uid'],
                        'money' => $mrs_order['money'],
                        'type' => 4, //回款
                        'order' => 'OD' . create_order(),
                        'status' => 1,
                        'crate_time' => time()
                    ];
                    $logModel->allowField(true)->save($log);
                    $project_info = $pModel->where(['id'=>$orderData['project_id']])->find();
                    $true_profit = ($project_info['true_profits']*100).'%';
                    $notice = '尊敬的会员：您好！我司已对'.$project_info['project_name'].'项目进行回款，该项目年化收益达'.$true_profit.',您本次收到本金'.$orderData['money'].'元+收益'.sprintf("%.2f",($mrs_order['money']-$orderData['money'])).'元合计'.$mrs_order['money'].'元。请您前往账户余额查看结算结果，谢谢支持！若有任何疑问请致电好融艺官方客服：400—605—9006';
                    TobeNotice($orderData['uid'], '退还通知', $notice);
                }
                ajaxReturn('兑付成功',1);
            }
        }else{
            ajaxReturn('错误操作');
        }
    }


    /**
     * 会员订单兑付批量操作
     * @param  $project_id 认投项目ID
     * @author hey_heyang(635870453@qq.com)
     */
    public function batchDuiFuOrderPay(){
        if(request()->isAjax() && request()->isPost()) {
            if(empty($_POST['project_id'])){ajaxReturn('参数错误');}
            $project_id = intval($_POST['project_id']);
            $orderModel = new Order();
            $dataList = $orderModel
                ->alias('a')
                ->field('a.uid,mrs.money,b.bizUserId,mr.order_no,mrs.order_id,mrs.id as mr_id')
                ->join('tf_member b', 'a.uid=b.id')
                ->join('tf_money_returns mrs', 'a.id=mrs.order_id')
                ->join('tf_money_return mr', 'mrs.return_id=mr.id')
                ->where(['a.project_id' => $project_id,'type'=>1, 'a.status' =>2, 'payment_status' => 1,'mrs.status'=>1,'mr.status'=>2])
                ->limit(100)
                ->select();
            $dataList= empty($dataList)?array():$dataList->toArray() ;
            //如果支持订单为空
            if (empty($dataList)) {
                ajaxReturn('未找到需要兑付的订单');
            }

            $YunClass = new Yunst();
            /*批次号*/
            $Olist['order'] = 'back' . str_pad($project_id, 4, '0', STR_PAD_LEFT);
            $list = [];
            foreach ($dataList as $value) {
                $list[] = $this->getDuiFuDaiList($project_id, $value['uid'], $value['money'], $value['bizUserId'],$value['order_id'],$value['mr_id']);
            }
            $Olist['list'] = $list;

            $res = $YunClass->batchPay($Olist);

            if ($res['status'] == 'OK') {
                ajaxReturn('操作成功', 1);
            } else {
                ajaxReturn($res['message']);
            }
        }else{
            ajaxReturn('错误操作');
        }
    }


    /**
     * 企业端提现列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function getTiXianList(){
        $where = [];
        if (isset($_GET['status']) && input('get.status') != 0) {
            $where['mc.status'] = ['eq', input('get.status')];
        }
        if (input('get.start_date')) {
            $where['mc.create_time'][] = ['gt', strtotime(input('get.start_date') . ' 00:00:00')];
        }
        if (input('get.end_date')) {
            $where['mc.create_time'][] = ['lt', strtotime(input('get.end_date') . ' 23:59:59')];
        }
        if (input('get.search')) {
            $where['pu.company_name'] = ['like', '%' . trim(input('get.search')) . '%'];
        }
        if (input('get._sort')) {
            $order = explode(',', input('get._sort'));
            $order = 'mc.' . $order[0] . ' ' . $order[1];
        } else {
            $order = 'mc.id desc';
        }
        $where['mc.type'] = 2;
        //导出
        if (input('get.down')) {
            $tableHeader = ['项目方名称', '手机号','订单号',  '开户行', '银行卡号', '金额', '状态', '创建时间'];
            $dataList = $this->mcModel
                ->alias('mc')
                ->join('tf_project_user pu', 'mc.company_id=pu.id')
                ->field('mc.*,FROM_UNIXTIME(mc.create_time) as time,pu.company_name,pu.mobile as company_mobile')
                ->where($where)
                ->order($order)
                ->select()
                ->toArray();
            $data = [];
            foreach ($dataList as $k => $v) {
                $data[$k]['company_name'] = $v['company_name'];
                $data[$k]['mobile'] = $v['mobile'];
                $data[$k]['order_num'] = $v['order_num'];
                $data[$k]['bank_name'] = $v['bank_name'];
                $data[$k]['bank_num'] = $v['bank_num'];
                $data[$k]['money'] = $v['money'];
                if ($v['status'] == 1) {
                    $data[$k]['status'] = '待审核';
                } elseif ($v['status'] == 2) {
                    $data[$k]['status'] = '待打款';
                } elseif ($v['status'] == 3) {
                    $data[$k]['status'] = '已打款';
                } elseif ($v['status'] == 4) {
                    $data[$k]['status'] = '已拒绝';
                }
                $data[$k]['time'] = $v['time'];
            }
            ToPHPEXECL($tableHeader, $data, '提现记录');
        }
        $dataList = $this->mcModel
                    ->alias('mc')
                    ->join('tf_project_user pu', 'mc.company_id=pu.id')
                    ->field('mc.*,FROM_UNIXTIME(mc.create_time) as time,pu.company_name,pu.mobile as company_mobile')
                    ->where($where)
                    ->order($order)
                    ->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    /**
     * 企业端提现代付操作
     * @author hey_heyang(635870453@qq.com)
     */
    private function companyTiXianDaiFu($id) {
        $YunClass = new Yunst();
        $Info = $this->mcModel->where(['id' =>$id])->find();
        $bizUserId = $this->puModel->where(['id' => $Info['company_id']])->value('bizUserId');
        $Info['bankCardNo']=$Info['bank_num'];
        $Info['order']=$Info['order_num'];
        $Info['is_company'] = 1;
        $message = $YunClass->TiMoney($bizUserId, $Info);
        if ($message['status'] == 'error') {
             ajaxReturn($message['message']);
        }
        if ($message['status'] == 'OK') {
            companyTobeNotice($Info['company_id'], '提现通知', '您的提现申请已成功,请随时留意银行信息。');
        }
    }



    /**
     * 企业端提现编辑
     * @author hey_heyang(635870453@qq.com)
     */
    public function editTiXian($id) {
        if (request()->isPost()) {
            $data=input('post.');
            if(empty($id)){
                ajaxReturn('参数错误');
            }
            if ($data['status'] == 2) {
                 $this->companyTiXianDaiFu($id);
            }else{
                $tixian_list = $this->mcModel->where(['id'=>$id])->find()->toArray();
                $this->puModel->where(['id'=>$tixian_list['company_id']])->setInc('money', $tixian_list['money']);
                $redis = Redis::instance();
                $token = $redis->get('user:' . $tixian_list['company_id']);
                $firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
                $firm_info['modify'] = true;
                $redis->hSet('firm_info', $token, json_encode($firm_info));
                companyTobeNotice($tixian_list['company_id'], '提现通知', '您发起的'.$tixian_list['money'].'元提现请求已被拒绝!');
            }
            $result = $this->mcModel->where(array('id'=>$id))->update(array('status'=>$data['status']));

            if ($result) {
                ajaxReturn(lang('action_success'), url('getTiXianList'));
            } else {
                 ajaxReturn($this->mcModel->getError());
            }
        } else {
            $data = $this->mcModel
                ->alias('mc')
                ->join('tf_project_user pu', 'mc.company_id=pu.id')
                ->field('mc.*,FROM_UNIXTIME(mc.create_time) as time,pu.company_name')
                ->where(array('mc.id'=>$id))
                ->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }


    /**
     * 后台新增项目方
     * @author hey_heyang(635870453@qq.com)
     */
    public function CreateProjectManager()
    {
        if(request()->isPost() && request()->isAjax()){
            if(!empty($_POST['company_name']) && !empty($_POST['company_intro']) && !empty($_POST['mobile'])){
                $pumodel = new ProjectUser();
                $data['mobile'] = trim($_POST['mobile']);
                $data['company_name'] = trim($_POST['company_name']);
                $data['company_intro'] = trim($_POST['company_intro']);
                $data['logo'] = trim($_POST['logo']);
                $result = $pumodel->registerProjectMember($data);
                if($result['status']>0){
                     ajaxReturn('注册成功', url('ProjectManage'));
                }else{
                     ajaxReturn($result['msg']);
                }
            }else{
                ajaxReturn('请将信息填写完整!');
            }
        }
        return $this->fetch();
    }


    /**
     * 项目方详情
     * @param  $id 项目方id
     * @author hey_heyang(635870453@qq.com)
     */
    public function DetailProjectManager($id)
    {
        if($id){
            $project_info = $this->puModel->where(array('id'=>$id))->find()->toArray();
            if(!empty($project_info)){
                $project_info['business_license_file_name']=$project_info['business_license'];
                $project_info['legal_person_id_front_file_name']=$project_info['legal_person_id_front'];
                $project_info['legal_person_id_back_file_name']=$project_info['legal_person_id_back'];
                $project_info['company_count_file_name']=$project_info['company_count'];
                $business_license=self::UPLOAD_SRC.$id.'/'.$project_info['business_license'];
                $legal_person_id_front=self::UPLOAD_SRC.$id.'/'.$project_info['legal_person_id_front'];
                $legal_person_id_back=self::UPLOAD_SRC.$id.'/'.$project_info['legal_person_id_back'];
                $company_count=self::UPLOAD_SRC.$id.'/'.$project_info['company_count'];
                $project_info['business_license']=$business_license;
                $project_info['legal_person_id_front']=$legal_person_id_front;
                $project_info['legal_person_id_back']=$legal_person_id_back;
                $project_info['company_count']=$company_count;
                $this->assign('project_info',$project_info);
                return $this->fetch();
            }
        }else{
            $this->redirect('ProjectManage');
        }
    }


    /**
     *提交通联页面详情
     * @param  $id 项目方id
     * @author hey_heyang(635870453@qq.com)
     */
    public function tonglian($id)
    {
        if($id){
            $project_info = $this->puModel->where(array('id'=>$id))->find();
            if(!empty($project_info)){
                $project_info['business_license_file_name']=$project_info['business_license'];
                $project_info['legal_person_id_front_file_name']=$project_info['legal_person_id_front'];
                $project_info['legal_person_id_back_file_name']=$project_info['legal_person_id_back'];
                $project_info['company_count_file_name']=$project_info['company_count'];
                $business_license=self::UPLOAD_SRC.$id.'/'.$project_info['business_license'];
                $legal_person_id_front=self::UPLOAD_SRC.$id.'/'.$project_info['legal_person_id_front'];
                $legal_person_id_back=self::UPLOAD_SRC.$id.'/'.$project_info['legal_person_id_back'];
                $company_count=self::UPLOAD_SRC.$id.'/'.$project_info['company_count'];
                $project_info['business_license']=$business_license;
                $project_info['legal_person_id_front']=$legal_person_id_front;
                $project_info['legal_person_id_back']=$legal_person_id_back;
                $project_info['company_count']=$company_count;
                $this->assign('project_info',$project_info);
                return $this->fetch();
            }
        }else{
            $this->redirect('ProjectManage');
        }
    }


    /**
     *项目方信息审核
     * @author hey_heyang(635870453@qq.com)
     */
    public function projectInfoTongLianConfirm()
    {
        if(request()->isAjax() && request()->isPost()){
            $id=intval($_POST['id']);
            $systerm_check = intval($_POST['systerm_check']);
            $systerm_msg = $_POST['systerm_msg'];
            if($id){
                $result = $this->puModel->confirmProjectInfo($id,$systerm_check,$systerm_msg);
                $redis = Redis::instance();
                $token = $redis->get('user:' . $id);
                $firm_info = json_decode($redis->hGet('firm_info' , $token) ,true);
                $firm_info['modify'] = true;
                $redis->hSet('firm_info', $token, json_encode($firm_info));
                if($result['status']>0){
                     ajaxReturn('操作成功', url('ProjectManage'));
                }else{
                     ajaxReturn($result['msg']);
                }
            }else{
                 ajaxReturn('参数错误');
            }
        }else{
             ajaxReturn('参数错误');
        }
    }


    /**
     *新增回款订单
     * @author hey_heyang(635870453@qq.com)
     */
    public function createOrder()     //新增订单 筛除还有未回款订单的项目
    {
            $where['id'] = ['not in',[1,2]];
            $data = $this->puModel->where($where)->select();
            $companyList = empty($data)?array():$data->toArray();
            $this->assign('companyList',$companyList);
        return $this->fetch();
    }

    /**
     *新增回款订单选择项目方时，获取其成功的认投项目列表
     * @author hey_heyang(635870453@qq.com)
     */
    public function getProjectList(){
        if(request()->isAjax() && request()->isPost()){
            if(intval($_POST['company_id'])>0){
                $res = $this->pModel->where(array('initiator'=>intval($_POST['company_id'])))->select();
                $list = empty($res)?array():$res->toArray();
                if(!empty($list)){
                    foreach($list as $key=>$value){
                        $mr_list = $this->mrModel->where(['project_id'=>$value['id'],'status'=>1])->find();
                        if(!empty($mr_list)){
                            unset($list[$key]);
                        }
                    }
                    $list = array_values($list);
                }
                $data['status'] =1;
                $data['list'] = $list;
                echo json_encode($data);
                exit;
            }else{
                ajaxReturn('参数错误');
            }

        }else{
            ajaxReturn('参数错误');
        }
    }

    /**
     *新增回款订单提交确认
     * @author hey_heyang(635870453@qq.com)
     */
    public function moneyReturnConfirm()
    {
        if(request()->isAjax() && request()->isPost()){
            if($_POST['company_id'] && $_POST['project_id'] && $_POST['money'] && $_POST['remarks']){
                $data['company_id']= intval($_POST['company_id']);
                $data['project_id'] = intval($_POST['project_id']);
                $data['money'] = floatval($_POST['money']);
                $data['remarks'] = $_POST['remarks'];
                $data['status'] = 1;
                $data['create_time'] = time();
                $data['order_no'] = createOrderNo('DS');
                $res =$this->mrModel->insert($data);
                if($res){
                    companyTobeNotice($data['company_id'], '回款', '您有一笔'.$data['money'].'的回款订单待支付!');
                    ajaxReturn('新增成功',url('projecthuikuan'));
                }else{
                    ajaxReturn('新增订单失败');
                }
            }else{
                ajaxReturn('参数错误');
            }

        }else{
            ajaxReturn('参数错误');
        }
    }


    /**
     *后台企业端文件下载
     * @author hey_heyang(635870453@qq.com)
     */
    public function downLoad($id,$fileName,$routeType=1){
        downLoad($id,$fileName,$routeType);
    }


    /**
     *后台企业端文件单独上传
     * @author hey_heyang(635870453@qq.com)
     */
    public function companyUpload()
    {
        if (request()->isPost()) {
            $file = request()->file('imgFile');
            if ($file) {
                $dir = 'projectuser' . DS . 'logo';
                $upload_res = companyUpload($file, $dir);
                $upload_res['fileName'] = str_replace('\\', '/', $upload_res['fileName']);
                if ($upload_res['status']) {
                    $data['logo'] = $upload_res['fileName'];
                    $data['logoSrc'] = '/uploads/projectuser/logo/' . $upload_res['fileName'];
                    ajaxReturn('上传成功', 1, '', $data);
                } else {
                    ajaxReturn('上传失败');
                }

            } else {
                ajaxReturn('请选择文件');
            }
        }
    }
}
